﻿using FlashPay.DAO.Shared;
using FlashPay.DAO.Bank;
using FlashPay.EF;
using FlashPay.EF.Models;
using FlashPay.Entity;
using FlashPay.Entity.Parameter;
using FlashPay.Util;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using FlashPay.Entity.DAORequest.Bank;

namespace FlashPay.DAO.Impl.Bank
{
    /// <summary>
    /// 銀行DAO
    /// </summary>
    public class BankInfoDAOImpl : BaseDAO, IDisposable, BankInfoDAO
    {
        public FlashPayContext dbContext { set; get; }

        public BankInfoDAOImpl()
        {
            this.dbContext = new FlashPayContext();
        }

        public BankInfoDAOImpl(FlashPayContext dbContext)
        {
            this.dbContext = dbContext;
        }

        public void Dispose()
        {
            if (this.dbContext != null)
            {
                this.dbContext.Dispose();
            }
        }

        /// <summary>
        /// 根据银行编码获取银行
        /// </summary>
        /// <param name="bankCode">银行编码</param>
        /// <returns>菜单</returns>
        public BankInfo GetByBankCode(string bankCode)
        {
            return dbContext.BankInfo.Where(x => x.BankCode == bankCode).FirstOrDefault();
        }

        /// <summary>
        /// 銀行新增
        /// </summary>
        public void Add(BaseModel<String> result, BankInfo model)
        {
            /* 確認資料存在 */
            IQueryable<BankInfo> _result = dbContext.BankInfo.Where(bank => bank.BankCode.Equals(model.BankCode));
            if (_result.Count() != 0)
                return;

            /* 呼叫資料庫 */
            dbContext.BankInfo.Add(model);
            dbContext.SaveChanges();

            /* 結果複製 */
            result.Success = true;
        }

        /// <summary>
        /// 銀行修改
        /// </summary>
        public void EditUseBankId(BaseModel<String> result, BankInfo model)
        {
            /* 確認資料存在 */
            IQueryable<BankInfo> _result = dbContext.BankInfo.Where(bank => bank.BankCode.Equals(model.BankCode));
            if (_result.Count() != 1)
                return;

            /* 轉換Model */
            BankInfo bankInfo = _result.First();
            bankInfo.BankName = model.BankName;
            bankInfo.BankFullName = model.BankFullName;
            bankInfo.BankEnglishName = model.BankEnglishName;
            bankInfo.SortNo = model.SortNo;
            bankInfo.BankUrl = model.BankUrl;
            bankInfo.BankRemark = model.BankRemark;
            bankInfo.BankTel = model.BankTel;
            bankInfo.BankAddress = model.BankAddress;

            /* 呼叫資料庫 */
            dbContext.SaveChanges();

            /* 結果複製 */
            result.Success = true;
        }

        public void Get(BaseModel<List<BankInfo>> result, BankInfo model)
        {
            BankInfoRequest model2 = new BankInfoRequest();
            model2.BankCode = model.BankCode;
            model2.BankName = model.BankName;
            model2.BankFullName = model.BankFullName;
            model2.BankEnglishName = model.BankEnglishName;
            model2.SortNo = model.SortNo;
            model2.BankUrl = model.BankUrl;
            model2.BankRemark = model.BankRemark;
            model2.BankTel = model.BankTel;
            model2.BankAddress = model.BankAddress;

            Get(result, model2);
        }

        public void Get(BaseModel<List<BankInfo>> result, BankInfoRequest model)
        {
            /* 呼叫資料庫 */
            IQueryable<BankInfo> _result = dbContext.BankInfo.Where(
                bank =>
                    (String.IsNullOrWhiteSpace(model.BankCode) || bank.BankCode.Equals(model.BankCode)) &&
                    (String.IsNullOrWhiteSpace(model.BankName) || bank.BankName.Contains(model.BankName)) &&
                    (String.IsNullOrWhiteSpace(model.BankFullName) || bank.BankFullName.Contains(model.BankFullName)) &&
                    (String.IsNullOrWhiteSpace(model.BankEnglishName) || bank.BankEnglishName.Contains(model.BankEnglishName)) &&
                    (String.IsNullOrWhiteSpace(model.BankUrl) || bank.BankUrl.Contains(model.BankUrl)) &&
                    (String.IsNullOrWhiteSpace(model.BankRemark) || bank.BankRemark.Contains(model.BankRemark)) &&
                    (String.IsNullOrWhiteSpace(model.BankTel) || bank.BankTel.Contains(model.BankTel)) &&
                    (String.IsNullOrWhiteSpace(model.BankAddress) || bank.BankAddress.Contains(model.BankAddress)) &&
                    (model.BankCodes == null || model.BankCodes.Contains(bank.BankCode)) &&
                    (!model.SortNo.HasValue || model.SortNo == model.SortNo)
            );

            List<BankInfo> list = Split(_result.OrderBy(bank => bank.SortNo), result.PageIndex, result.PageSize);
            Int32 totalCount = _result.Count();

            /* 結果複製 */
            result.Success = true;
            result.TotalCount = totalCount;
            result.Result = list;
        }

        /// <summary>
        /// 分頁查詢所有銀行卡
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public PagedList<BankInfo> GetList(BankInfoQuery query)
        {
            PagedList<BankInfo> result = new PagedList<BankInfo>();
            try
            {
                List<BankInfo> bank = null;
                MemoryCacheUtil mcu = new MemoryCacheUtil();
                string cacheKey = "BANKINFO";

                //if (mcu.Get(cacheKey) != null)
                //{
                //    bank = mcu.Get<List<BankInfo>>(cacheKey);
                //}
                //else
                //{
                //    
                //    mcu.Set(cacheKey, bank, TimeSpan.FromDays(7));
                //}
                bank = dbContext.BankInfo.OrderBy(banks => banks.SortNo).ToList();
                if (!string.IsNullOrEmpty(query.BankCode))
                {
                    bank = bank.Where(c => c.BankCode.Contains(query.BankCode)).ToList();
                }
                if (!string.IsNullOrEmpty(query.BankName))
                {
                    bank = bank.Where(c => c.BankName.Contains(query.BankName)).ToList();
                }
                if (!string.IsNullOrEmpty(query.BankFullName))
                {
                    bank = bank.Where(c => c.BankFullName == query.BankFullName).ToList();
                }
                if (!string.IsNullOrEmpty(query.BankEnglishName))
                {
                    bank = bank.Where(c => c.BankEnglishName == query.BankEnglishName).ToList();
                }
                int currentPageIndex = query.CurrentPageIndex.Value;
                int pageSize = query.PageSize.Value;

                List<EF.Models.BankInfo> list = bank.OrderBy(b => b.SortNo).Skip((currentPageIndex - 1) * pageSize).Take(pageSize).ToList();
                result.TotalCount = bank.Count();
                result.TData = list;
                result.Success = true;
            }
            catch (Exception ex)
            {
                result.Success = false;
                result.ErrorMessage = "服务器异常";
            }
            return result;
        }

        /// <summary>
        /// 获取所有銀行信息
        /// </summary>
        /// <param name="query">查询条件</param>
        /// <returns>List<BankInfo></returns>
        public List<BankInfo> GetBankInfoList()
        {
            List<BankInfo> result = new List<BankInfo>();
            var CList = dbContext.BankInfo.OrderBy(bank => bank.SortNo).ToList();
            result = CList;
            return result;
        }
        /// <summary>
        /// 根据编号获取银行信息
        /// </summary>
        /// <param name="BankCode">银行代码</param>
        /// <returns>BankInfo</returns>
        public BankInfo GetBankInfoByBankCode(string BankCode)
        {
            BankInfo result = dbContext.BankInfo.Where(x => x.BankCode == BankCode).FirstOrDefault();
            return result;
        }
        /// <summary>
        /// 新增银行信息
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public JResult AddBankInfo(BankInfo model)
        {
            var result = new JResult()
            {
                Success = false
            };
            if (dbContext.BankInfo.Where(b => b.BankCode == model.BankCode).Count() == 0)//如果沒有該銀行信息則新增
            {
                dbContext.BankInfo.Add(model);
                dbContext.SaveChanges();
                result.Success = true;
                List<BankInfo> bank = null;
                MemoryCacheUtil mcu = new MemoryCacheUtil();
                string cacheKey = "BANKINFO";
                bank = dbContext.BankInfo.OrderBy(banks => banks.SortNo).ToList();
                mcu.Set(cacheKey, bank, TimeSpan.FromDays(7));
            }
            else if (dbContext.BankInfo.Where(b => b.BankCode == model.BankCode).Count() == 1)//如果存在該銀行信息
            {
                BankInfo bi = dbContext.BankInfo.Where(x => x.BankCode == model.BankCode).FirstOrDefault();
                result.ErrorMessage = "已存在该银行Code信息";
            }
            return result;
        }
        /// <summary>
        /// 修改銀行信息
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public bool UpdateBankInfo(BankInfo model)
        {
            bool result = false;

            BankInfo bankInfo = dbContext.BankInfo.Find(model.BankCode);

            bankInfo.BankCode = model.BankCode;
            bankInfo.BankName = model.BankName;
            bankInfo.BankFullName = model.BankFullName;
            bankInfo.BankEnglishName = model.BankEnglishName;
            bankInfo.SortNo = model.SortNo;
            bankInfo.BankUrl = model.BankUrl;
            bankInfo.BankRemark = model.BankRemark;
            bankInfo.BankTel = model.BankTel;
            bankInfo.BankAddress = model.BankAddress;
            if (dbContext.SaveChanges() >= 0)
            {
                result = true;
                List<BankInfo> bank = null;
                MemoryCacheUtil mcu = new MemoryCacheUtil();
                string cacheKey = "BANKINFO";
                bank = dbContext.BankInfo.OrderBy(banks => banks.SortNo).ToList();
                mcu.Set(cacheKey, bank, TimeSpan.FromDays(7));
            }
            return result;
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="bankCode">银行代码</param>
        /// <returns></returns>
        public bool Delete(string bankCode, out bool isUse)
        {
            bool result = false;
            isUse = false;
            BankInfo bankInfo = dbContext.BankInfo.Find(bankCode);

            if (bankInfo != null)
            {
                if (dbContext.BankCard.Any(o => o.BankCode == bankCode))
                {
                    isUse = true;
                }
                else
                {
                    dbContext.BankInfo.Remove(bankInfo);
                    if (dbContext.SaveChanges() > 0)
                    {
                        result = true;
                        List<BankInfo> bank = null;
                        MemoryCacheUtil mcu = new MemoryCacheUtil();
                        string cacheKey = "BANKINFO";
                        bank = dbContext.BankInfo.OrderBy(banks => banks.SortNo).ToList();
                        mcu.Set(cacheKey, bank, TimeSpan.FromDays(7));
                    }
                }
            }
            return result;
        }

        //根据bankcode字符串查询中文银行名称
        public string GetBankNameByStr(string withdrawalBank)
        {
            if (string.IsNullOrEmpty(withdrawalBank)) return "";
            List<string> bankList = withdrawalBank.Split(',').ToList();
            if (bankList.Count <= 0) return "";
            string newBankStr = string.Empty;
            var item = dbContext.BankInfo.Where(e => bankList.Contains(e.BankCode)).Distinct()
                .OrderBy(e=>e.SortNo).Select(e=>e.BankName).ToList();

            if (item == null || item.Count <= 0) return "";

            for (int z = 0; z < item.Count; z++)
            {
                newBankStr += item[z] + ",";
            }
            newBankStr = newBankStr.TrimEnd(',');
            return newBankStr;
        }
    }
}
